package com.springboot.cloud.sysadmin.organization.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.cloud.sysadmin.organization.dao.UserRoleMapper;
import com.springboot.cloud.sysadmin.organization.entity.po.UserRole;
import com.springboot.cloud.sysadmin.organization.service.IUserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
@Service
@Slf4j
public class UserRoleService extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private   RoleService roleService;

    @Override
    public boolean saveBatch(String userId, Set<String> roles) {
        if (ArrayUtil.isNotEmpty(queryByUserId(userId))) {
            removeByUserId(userId);
        }
        if (ArrayUtil.isEmpty(roles)) {
            roles.add("1284060496206516226");
            Set<UserRole> userRoles = roles.stream().map(roleId -> new UserRole(userId, roleId)).collect(Collectors.toSet());
            return saveBatch(userRoles);
        }
        log.debug("user.geaaatId():{}", roles);
        Set<UserRole> userRoles = roles.stream().map(roleId -> new UserRole(userId, roleId)).collect(Collectors.toSet());
        log.debug("user.getddId():{}", roles);
        return saveBatch(userRoles);
    }

    @Override
    public boolean removeByUserId(String userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getUserId, userId);
        return remove(queryWrapper);
    }

    @Override
    public boolean removeByRoleId(String roleId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getRoleId, roleId);
        return remove(queryWrapper);
    }

    // 根据用户id查询用户所拥有的角色信息
    @Override
    public Set<String> queryByUserId(String userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserRole> userRoleList = list(queryWrapper);
        Set<String> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        log.debug("roles:{}", roleIds);
        Set<String> availableRole = new TreeSet<String>();
        for (String str : roleIds) {
            if (roleService.getRole(str).getEnabled()) {
                availableRole.add(str);
            }
        }
        log.debug("availableRole:{}", availableRole);
        return availableRole;
    }

}
